<template>
  <view>
    <block v-if="canvas_show">
      <view class="head_title"> 维修服务报告 </view>
      <view class="same_ful">
        <view class="ful_row">
          <text class="ful_left">工单号:</text>
          <text class="ful_right">{{ detail_.workID }}</text>
        </view>
        <view class="ful_row">
          <text>日期:</text>
          <text>{{ detail_.time }}</text>
        </view>
      </view>
      <view class="border_"> </view>
      <!-- 	<view class="title_">
				客户及产品信息
			</view> -->
      <view class="same_ful">
        <view class="ful_row">
          <text class="ful_left">客户名称:</text>
          <text class="ful_right">{{ detail_.name }}</text>
        </view>
        <view class="ful_row">
          <text>设备名称:</text>
          <text>{{ detail_.equipment_name || "暂无" }}</text>
        </view>
      </view>
      <view class="same_ful">
        <view class="ful_row">
          <text class="ful_left">型号:</text>
          <text class="ful_right">{{ detail_.equipment_marking || "暂无" }}</text>
        </view>
        <view class="ful_row">
          <text class="ful_left">软件版本:</text>
          <text class="ful_right">{{ detail_.software_version || "暂无" }}</text>
        </view>
        <!-- 	<view class="ful_row">
					<text>系统编号:</text>
					<text>{{detail_.system_number||'暂无'}}</text>
				</view> -->
      </view>
      <!-- <view class="same_ful">
				<view class="ful_row">
					<text class="ful_left">软件版本:</text>
					<text class="ful_right">{{detail_.software_version||'暂无'}}</text>
				</view>
			</view> -->
      <view class="same_ful">
        <view class="ful_row">
          <text class="ful_left">序列号:</text>
          <text class="ful_right">{{ detail_.serial || "暂无" }}</text>
        </view>
      </view>
      <!-- <view class="same_ful">
				<view class="ful_row">
					<text class="ful_left">设备附件信息：</text>
				</view>
			</view>
			<view class="content_" style="padding-bottom: 20rpx;">
				<view class="content_title">
				{{detail_.ending||'暂无'}}
			</view>
				<view class="content_imgs">
					<image :src="i" mode="" v-for="(i,l) in detail_.images" :key='l'></image>
				</view>
			</view> -->
      <view class="border_"> </view>
      <view class="title_"> 服务信息 </view>
      <view class="one_">
        <view class="one_left"> 客户报修时间 </view>
        <view class="one_right">
          {{ detail_.createtime || "暂无" }}
        </view>
      </view>
      <view class="one_">
        <view class="one_left"> 工程师到达时间 </view>
        <view class="one_right">
          {{ detail_.present_time || "暂无" }}
        </view>
      </view>
      <view class="one_">
        <view class="one_left"> 设备合同状态 </view>
        <view class="one_right">
          {{ detail_.contract_status || "暂无" }}
        </view>
      </view>
      <view class="one_">
        <view class="one_left"> 服务类型 </view>
        <view class="one_right">
          {{ detail_.service_type || "暂无" }}
        </view>
      </view>
      <!-- 	<view class="one_" v-if="detail_.warranty_time!=0">
				<view class="one_left">
					服务日期
				</view>
				<view class="one_right">
					{{detail_.warranty_time||'暂无'}}
				</view>
			</view> -->
      <view class="border_"> </view>
      <view class="two_">
        <view class="two_left"> 客户报修内容： </view>
        <view class="two_right">
          {{ detail_.content || "未获取到信息" }}
        </view>
      </view>
      <view class="border_"> </view>
      <view class="two_">
        <view class="two_left"> 维修记录： </view>
        <block v-if="detail_.repair.length > 0">
          <view class="two_right" v-for="(item, index) in detail_.repair" :key="index">
            {{ index + 1 + "." + item.repair || "未获取到信息" }}
          </view>
        </block>
        <block v-else> 暂无最新消息 </block>
      </view>
      <view class="border_"> </view>
      <view class="two_">
        <view class="two_left"> 维修结果及建议： </view>
        <view class="two_right">
          {{ detail_.ending }}
        </view>
      </view>
      <view class="border_"> </view>
      <view class="sign">
        <view class=""> 客户签字(点击代签字) </view>
        <view class=""> 工程师签字 </view>
      </view>
      <view class="sign_ture">
        <view class="sign_ture_user" @tap="jump_qianming">
          <!-- <Signature ref="sig" v-model="v"></Signature> -->
          <image
            :src="detail_.image"
            style="width: 100%; height: 100%; z-index: 99"
            mode="aspectFit"
            v-if="detail_.image"
          ></image>
          <!-- <image :src="imgSrc" style="width: 100%;height: 100%;z-index: 99;" mode="aspectFit" v-else></image> -->
          <canvas
            style="
              position: absolute;
              left: 0;
              width: 325rpx;
              bottom: 0;
              width: 325rpx;
              height: 183rpx;
            "
            canvas-id="handWriting2"
            v-else
          ></canvas>
        </view>
        <view class="sign_ture_engineer">
          {{ detail_.nickname }}
        </view>
      </view>
      <view class="border_"> </view>
      <view class="cont_">
        备注：本函仅针对该工单所反馈问题做确认操作，签字后该工单即变更为完结状态，如有其他问题请重新发起报修，谢谢
      </view>
      <view
        class="submit"
        @tap="submit"
        :style="{
          color: detail_.image ? '#1a66ff!important' : '',
          backgroundColor: detail_.image ? '#f5f6f8!important' : '',
        }"
      >
        {{ detail_.image ? "已提交" : "提交" }}
      </view>
      <!-- <view class="getPoster">
        <button
          class="btn-big"
          style="
            margin: 15px 0;
            background: #1a66ff;
            color: #fff;
            width: 100%;
            padding: 5px;
          "
          size="mini"
          @tap="down"
          v-if="detail_.image"
        >
          生成图片
        </button>
      </view> -->
    </block>
    <view class="wrapper" v-else>
      <view class="handBtn">
        <image
          @click="selectColorEvent('black', '#1A1A1A')"
          :src="
            selectColor === 'black'
              ? '/static/other/color_black_selected.png'
              : '/static/other/color_black.png'
          "
          :class="[selectColor === 'black' ? 'color_select' : '', 'black-select']"
        ></image>
        <image
          @click="selectColorEvent('red', '#ca262a')"
          :src="
            selectColor === 'red'
              ? '/static/other/color_red_selected.png'
              : '/static/other/color_red.png'
          "
          :class="[selectColor === 'red' ? 'color_select' : '', 'black-select']"
        ></image>
        <button @click="retDraw" class="delBtn">重写</button>
        <!-- 		<button @click="saveCanvasAsImg" class="saveBtn">保存</button> -->
        <!-- <button @click="previewCanvasImg" class="previewBtn">预览</button> -->
        <button @click="subCanvas" class="subBtn">完成</button>
      </view>
      <view class="handCenter">
        <canvas
          class="handWriting"
          :disable-scroll="true"
          @touchstart="uploadScaleStart"
          @touchmove="uploadScaleMove"
          canvas-id="handWriting"
        ></canvas>
        <!-- <canvas style="position: absolute" :style="{ width: cavWidth, height: cavWidth1 ,display:'none'}"
					canvas-id="handWriting2"></canvas> -->
      </view>
      <view class="handRight">
        <view class="handTitle">请签名</view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapMutations } from "vuex";
import config from "@/request/config.js";
export default {
  data() {
    return {
      canvasName: "handWriting",
      ctx: "",
      startX: null,
      startY: null,
      canvasWidth: 0,
      canvasHeight: 0,
      selectColor: "black",
      lineColor: "#1A1A1A", // 颜色
      lineSize: 5, // 笔记倍数
      canvas_show: true, //画布显示隐藏
      imgSrc: "", //签名数据
      warranty_id: null, //工单id
      service_id: null, //维修id
      report_id: null, //维修报告id
      detail_: {}, //页面详情
      shareImg: true,
    };
  },
  onLoad(e) {
    this.ctx = uni.createCanvasContext("handWriting");
    this.$nextTick(() => {
      uni
        .createSelectorQuery()
        .select(".handCenter")
        .boundingClientRect((rect) => {
          this.canvasWidth = rect.width;
          this.canvasHeight = rect.height;
          /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
          this.setCanvasBg("#fff");
        })
        .exec();
    });
    this.warranty_id = e.warranty_id;
    this.service_id = e.service_id;
    this.report_id = e.report_id;
    this.getdata();
  },
  methods: {
    ...mapMutations(["setReportDetail"]),
    // down() {
    //   uni.navigateTo({
    //     url: "/pages/share/share?id=" + this.report_id + "&shareImg=" + this.shareImg,
    //   });
    // },
    jump_qianming() {
      /* 	uni.navigateTo({
						url: '../qianming/qianming'
					}) */
      if (!this.detail_.image) this.canvas_show = !this.canvas_show;
    },
    // 笔迹开始
    uploadScaleStart(e) {
      this.startX = e.changedTouches[0].x;
      this.startY = e.changedTouches[0].y;
      //设置画笔参数
      //画笔颜色
      this.ctx.setStrokeStyle(this.lineColor);
      //设置线条粗细
      this.ctx.setLineWidth(this.lineSize);
      //设置线条的结束端点样式
      this.ctx.setLineCap("round"); //'butt'、'round'、'square'
      //开始画笔
      this.ctx.beginPath();
    },
    // 笔迹移动
    uploadScaleMove(e) {
      //取点
      let temX = e.changedTouches[0].x;
      let temY = e.changedTouches[0].y;
      //画线条
      this.ctx.moveTo(this.startX, this.startY);
      this.ctx.lineTo(temX, temY);
      this.ctx.stroke();
      this.startX = temX;
      this.startY = temY;
      this.ctx.draw(true);
    },
    /**
     * 重写
     */
    retDraw() {
      this.ctx.clearRect(0, 0, 700, 730);
      this.ctx.draw();
      //设置canvas背景
      this.setCanvasBg("#fff");
    },
    /**
     * @param {Object} str
     * @param {Object} color
     * 选择颜色
     */
    selectColorEvent(str, color) {
      this.selectColor = str;
      this.lineColor = color;
    },
    //完成
    subCanvas() {
      this.canvas_show = !this.canvas_show;
      const token = uni.getStorageSync("userInfo").token;
      const _this = this;
      uni.canvasToTempFilePath({
        canvasId: "handWriting",
        fileType: "png",
        quality: 1, //图片质量
        success: (res) => {
          console.log(res.tempFilePath);
          // this.imgSrc = res.tempFilePath
          wx.getImageInfo({
            // 获取图片的信息
            src: res.tempFilePath,
            success: (res1) => {
              // console.log(res1)
              // 将canvas1的内容复制到canvas2中
              let canvasContext = wx.createCanvasContext("handWriting2");
              let rate = res1.height / res1.width;
              let width = 190 / rate;
              let height = 190;
              _this.cavWidth = 300 / rate;
              _this.cavWidth1 = 300;
              canvasContext.translate(height / 2, width / 2);
              canvasContext.rotate((270 * Math.PI) / 180);
              canvasContext.drawImage(
                res.tempFilePath,
                -width / 2,
                -height / 2,
                width,
                height
              );
              canvasContext.draw(false, () => {
                // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
                wx.canvasToTempFilePath({
                  // 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
                  canvasId: "handWriting2",
                  fileType: "png",
                  quality: 1, //图片质量
                  success(res2) {
                    // 调用uni.uploadFile上传图片即可
                    console.log(res2.tempFilePath, 3333);
                    _this.imgSrc = res2.tempFilePath;
                  },
                });
              });
              // _this.$nextTick(() => {
              // 	wx.canvasToTempFilePath({
              // 				canvasId: 'handWriting2',
              // 				fileType: 'png',
              // 				quality: 1, //图片质量
              // 				success(res3) {
              // 					// 调用uni.uploadFile上传图片即可
              // 					console.log(res3.tempFilePath,3333)
              // 					this.imgSrc = res3.tempFilePath
              // 				}
              // 			})
              // });
            },
          });
          /* 	uni.uploadFile({
								url: 'http://ylsb.xibuts.cn/api/common/upload', //仅为示例，非真实的接口地址
								filePath: res.tempFilePath,
								name: 'file',
								formData: {
									token: token // 上传附带参数
								},
								success: (res1) => {
									this.imgSrc=JSON.parse(res1.data).data.fullurl
								},
								fail: res3 => {
									uni.showToast({
										title:'上传失败',
										duration:1500,
										icon:'error'
									})
								}
							}); */

          // console.log(res.tempFilePath, 'canvas生成图片地址');
          /* 	uni.showToast({
								title: '以保存'
							}); */
          //保存到系统相册
          /* uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已成功保存到相册',
									duration: 2000
								});
							}
						}); */
        },
      });
    },
    rotate(cb) {
      const that = this;
      wx.createSelectorQuery()
        .select("#handWriting2")
        .fields({
          node: true,
          size: true,
        })
        .exec((res) => {
          const rotateCanvas = res[0].node;
          const rotateCtx = rotateCanvas.getContext("2d");
          //this.ctxW-->所绘制canvas的width
          //this.ctxH -->所绘制canvas的height
          rotateCanvas.width = this.ctxH;
          rotateCanvas.height = this.ctxW;
          wx.canvasToTempFilePath({
            canvas: that.canvas,
            success(res) {
              const img = rotateCanvas.createImage();
              img.src = res.tempFilePath;
              img.onload = function () {
                rotateCtx.translate(rotateCanvas.width / 2, rotateCanvas.height / 2);
                rotateCtx.rotate((270 * Math.PI) / 180);
                rotateCtx.drawImage(
                  img,
                  -rotateCanvas.height / 2,
                  -rotateCanvas.width / 2
                );
                rotateCtx.scale(that.pixelRatio, that.pixelRatio);
                cb(rotateCanvas);
              };
            },
            fail(err) {
              console.log(err);
            },
          });
        });
    },
    //保存到相册
    saveCanvasAsImg() {
      uni.canvasToTempFilePath({
        canvasId: "handWriting",
        fileType: "png",
        quality: 1, //图片质量
        success(res) {
          console.log(res.tempFilePath, "canvas生成图片地址");
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              uni.showToast({
                title: "已保存到相册",
                duration: 2000,
              });
            },
          });
        },
      });
    },
    //预览
    previewCanvasImg() {
      uni.canvasToTempFilePath({
        canvasId: "handWriting",
        fileType: "jpg",
        quality: 1, //图片质量
        success(res) {
          uni.previewImage({
            urls: [res.tempFilePath], //预览图片 数组
          });
        },
      });
    },
    //设置canvas背景色  不设置  导出的canvas的背景为透明
    //@params：字符串  color
    setCanvasBg(color) {
      /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
      //rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
      //这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
      this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
      // ctx.setFillStyle('red')
      this.ctx.setFillStyle(color);
      this.ctx.fill(); //设置填充
      this.ctx.draw(); //开画
    },
    /* 获取结单数据 */
    getdata() {
      this.$https
        .post("/warranty/seesign", {
          service_id: this.service_id,
        })
        .then((res) => {
          //contract_status 合同状态:0=技术保合同,1=无合同,2=标准:白金合同,3=单次合同
          //service_type 服务类型:0=维修,1=保养,2=安装
          this.detail_ = res.data;
          this.detail_.contract_status = this.changeContract(
            this.detail_.contract_status
          );
          this.detail_.service_type = this.changeService(this.detail_.service_type);
          this.shareImg = res.data.report ? false : true;
          let setData = this.detail_;
          this.setReportDetail(setData);
          // console.log(this.$store.state.reportDetail,'store')
        });
    },
    /* 转化 合同状态  */
    changeContract(i) {
      switch (i) {
        case "0":
          return "技术保合同";
        case "1":
          return "无合同";
        case "2":
          return "标准白金合同";
        case "3":
          return "单次合同";
      }
    },
    /* 转换 服务类型 */
    changeService(i) {
      switch (i) {
        case "0":
          return "维修";
        case "1":
          return "保养";
        case "2":
          return "安装";
      }
    },
    /* 提交 */
    submit() {
      if (!this.detail_.image) {
        const token = uni.getStorageSync("userInfo").token;
        uni.uploadFile({
          url: config.baseUrl + "/common/upload",
          filePath: this.imgSrc,
          name: "file",
          formData: {
            token: token, // 上传附带参数
          },
          success: (res1) => {
            let imgs = JSON.parse(res1.data).data.fullurl;
            this.$https
              .post("/warranty/signature", {
                warranty_id: this.detail_.warranty_id, //	工单id
                service_id: this.service_id, //维修id
                report_id: this.report_id, //维修报告id
                image: imgs,
              })
              .then((res) => {
                uni.showToast({
                  title: res.msg,
                  duration: 1500,
                  icon: "none",
                });
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1,
                  });
                }, 1500);
              });
          },
          fail: (res3) => {
            uni.showToast({
              title: "签名上传失败",
              duration: 1500,
              icon: "error",
            });
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.submit {
  width: 100%;
  height: 98rpx;
  text-align: center;
  background-color: $public-oclor;
  line-height: 98rpx;
  font-size: 32rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
}

.cont_ {
  font-size: 24rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #969699;
  margin: 32rpx;
}

.sign_ture_engineer {
  width: 325rpx;
  height: 183rpx;
  text-align: center;
  background-color: #f5f6f8;
  font-size: 32rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 550;
  line-height: 183rpx;
  font-family: "楷体";
  color: #000000;
}

.sign_ture {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  margin: 30rpx 0;
  position: relative;
}

.sign_ture_user {
  width: 325rpx;
  height: 183rpx;
  background-color: #f5f6f8;
}

.sign {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #303030;
  padding: 0 32rpx;
}

.sign > view {
  flex: 1;
  text-align: center;
  margin: 30rpx 0;
}

.border_ {
  height: 2rpx;
  margin: 0 32rpx;
  background-color: #ebeef1;
}

.getPoster {
  padding: 0 30px;
}

.head_title {
  font-size: 28rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #969699;
  line-height: 40rpx;
  padding: 32rpx;
  background-color: #f7f8fb;
  text-align: center;
}

.same_ful {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32rpx;
  font-size: 24rpx;
  margin: 16rpx 0 16rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  letter-spacing: 2rpx;

  .ful_row {
    width: 50%;

    .ful_left {
      color: #969699;
      margin-right: 10rpx;
    }

    .ful_right {
    }
  }
}

.title_ {
  font-size: 32rpx;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #303030;
  padding: 0 32rpx;
  margin: 32rpx 0;
}

.content_ {
  padding: 0 32rpx;

  .content_title {
    font-size: 24rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #3b3d3d;
  }

  .content_imgs {
    image {
      width: 160rpx;
      height: 160rpx;
      margin-right: 20rpx;
    }
  }
}

.one_ {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  margin: 16rpx 0 16rpx;

  .one_left {
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #969699;
  }

  .one_right {
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000000;
  }
}

.two_ {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 32rpx;
  margin: 16rpx 0 16rpx;
  font-size: 24rpx;
  .two_left {
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #969699;
    margin-bottom: 16rpx;
  }

  .two_right {
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000000;
    word-wrap: break-word;
  }
}

page {
  background: #fbfbfb;
  height: auto;
  overflow: hidden;
}

.wrapper {
  width: 100%;
  height: 95vh;
  margin: 30rpx 0;
  overflow: hidden;
  display: flex;
  align-content: center;
  flex-direction: row;
  justify-content: center;
  font-size: 28rpx;
}

.handWriting {
  background: #fff;
  width: 100%;
  height: 95vh;
}

.handRight {
  display: inline-flex;
  align-items: center;
}

.handCenter {
  border: 4rpx dashed #e9e9e9;
  flex: 5;
  overflow: hidden;
  box-sizing: border-box;
}

.handTitle {
  transform: rotate(90deg);
  flex: 1;
  color: #666;
}

.handBtn button {
  font-size: 28rpx;
}

.handBtn {
  height: 95vh;
  display: inline-flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: space-between;
  flex: 1;
}

.delBtn {
  position: absolute;
  top: 250rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #666;
}

.delBtn image {
  position: absolute;
  top: 13rpx;
  left: 25rpx;
}

.subBtn {
  position: absolute;
  bottom: 52rpx;
  left: -3rpx;
  display: inline-flex;
  transform: rotate(90deg);
  background: #008ef6;
  color: #fff;
  margin-bottom: 30rpx;
  text-align: center;
  justify-content: center;
}

/*Peach - 新增 - 保存*/

.saveBtn {
  position: absolute;
  top: 375rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #666;
}

.previewBtn {
  position: absolute;
  top: 500rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #666;
}

.uploadBtn {
  position: absolute;
  top: 625rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #666;
}

/*Peach - 新增 - 保存*/

.black-select {
  width: 60rpx;
  height: 60rpx;
  position: absolute;
  top: 30rpx;
  left: 25rpx;
}

.black-select.color_select {
  width: 90rpx;
  height: 90rpx;
  top: 100rpx;
  left: 10rpx;
}

.red-select {
  width: 60rpx;
  height: 60rpx;
  position: absolute;
  top: 140rpx;
  left: 25rpx;
}

.red-select.color_select {
  width: 90rpx;
  height: 90rpx;
  top: 120rpx;
  left: 10rpx;
}
</style>
